package com.hanxiaozhang.hash;

import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈一致性哈希，考虑各个机器的性能〉
 *
 * @author hanxinghua
 * @create 2022/12/29
 * @since 1.0.0
 */
public class ConsistencyHashingLoadFactor {


    public static void main(String[] args) {

        // 模拟客户端的请求
        String[] nodes = {"127.0.0.1", "10.9.3.253", "192.168.10.1"};

        System.out.println("---- ---- ---- ---- ----");
        for (String node : nodes) {
            System.out.println("[" + node + "]的hash值为" + getHash(node) + ", 被路由到结点[" + getServer(node) + "]");
        }
        System.out.println("---- ---- ---- ---- ----");

        // 模拟服务器上线
        addNode(new Machine("192.168.1.7", "8080", LoadFactor.MEMORY_16G));
        // 模拟服务器下线
        delNode(new Machine("192.168.1.1", "8080", LoadFactor.MEMORY_8G));

        System.out.println("---- ---- ---- ---- ----");
        for (String node : nodes) {
            System.out.println("[" + node + "]的hash值为" + getHash(node) + ", 被路由到结点[" + getServer(node) + "]");
        }
        System.out.println("---- ---- ---- ---- ----");
    }

    /**
     * 真实节点列表
     */
    private final static List<Machine> REAL_NODES = new ArrayList();

    /**
     * 虚拟节点，key是Hash值，value是虚拟节点信息
     */
    private final static SortedMap<Integer, String> SHARDS = new TreeMap();

    /**
     * 初始化数据
     */
    static {
        addNode(new Machine("192.168.1.1", "8080", LoadFactor.MEMORY_8G));
        addNode(new Machine("192.168.1.2", "8080", LoadFactor.MEMORY_16G));
        addNode(new Machine("192.168.1.3", "8080", LoadFactor.MEMORY_32G));
        addNode(new Machine("192.168.1.4", "8080", LoadFactor.MEMORY_16G));
    }

    /**
     * 获取被分配的节点名
     *
     * @param key
     * @return
     */
    public static Machine getServer(String key) {
        int hash = getHash(key);
        Integer node = null;
        SortedMap<Integer, String> subMap = SHARDS.tailMap(hash);
        if (subMap.isEmpty()) {
            node = SHARDS.lastKey();
        } else {
            node = subMap.firstKey();
        }
        String virtualNode = SHARDS.get(node);
        String realNodeName = virtualNode.substring(0, virtualNode.indexOf("&&"));
        for (Machine machine : REAL_NODES) {
            if (machine.getHost().equals(realNodeName)) {
                return machine;
            }
        }
        return null;
    }

    /**
     * 添加节点
     *
     * @param node
     */
    public static void addNode(Machine node) {
        if (!REAL_NODES.contains(node)) {
            REAL_NODES.add(node);
            System.out.println("真实节点[" + node + "] 上线添加");
            for (int i = 0; i < node.getMemory().getVrNum(); i++) {
                String virtualNode = node.getHost() + "&&VN" + i;
                int hash = getHash(virtualNode);
                SHARDS.put(hash, virtualNode);
                System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + " 被添加");
            }
        }
    }

    /**
     * 删除节点
     *
     * @param node
     */
    public static void delNode(Machine node) {
        String host = node.getHost();
        Iterator<Machine> it = REAL_NODES.iterator();
        while (it.hasNext()) {
            Machine machine = it.next();
            if (machine.getHost().equals(host)) {
                it.remove();
                System.out.println("真实节点[" + node + "] 下线移除");
                for (int i = 0; i < node.getMemory().getVrNum(); i++) {
                    String virtualNode = node.getHost() + "&&VN" + i;
                    int hash = getHash(virtualNode);
                    SHARDS.remove(hash);
                    System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + " 被移除");
                }
            }
        }
    }

    /**
     * FNV1_32_HASH算法
     */
    private static int getHash(String str) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < str.length(); i++) {
            hash = (hash ^ str.charAt(i)) * p;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        // 如果算出来的值为负数则取其绝对值
        if (hash < 0) {
            hash = Math.abs(hash);
        }
        return hash;
    }

}


/**
 * 机器类
 */
class Machine {

    public Machine(String host, String port, LoadFactor memory) {
        this.host = host;
        this.port = port;
        this.memory = memory;
    }

    private String host;

    private String port;

    private LoadFactor memory;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public LoadFactor getMemory() {
        return memory;
    }

    public void setMemory(LoadFactor memory) {
        this.memory = memory;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Machine machine = (Machine) o;
        return Objects.equals(host, machine.host) && Objects.equals(port, machine.port);
    }

    @Override
    public int hashCode() {
        return Objects.hash(host, port);
    }

    @Override
    public String toString() {
        return "Machine{" +
                "host='" + host + '\'' +
                ", port='" + port + '\'' +
                ", memory=" + memory +
                '}';
    }
}

/**
 * 负载因子
 */
enum LoadFactor {

    MEMORY_8G(5), MEMORY_16G(10), MEMORY_32G(20);

    private int vrNum;

    private LoadFactor(int vrNum) {
        this.vrNum = vrNum;
    }

    public int getVrNum() {
        return vrNum;
    }

}
